<html lang="zh-cn">
<!DOCTYPE html>
<head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<meta name="description" content="">
	<meta name="author" content="Guo Yinxin">

	<link rel="shortcut icon" href="icons/monitor.ico">

	<!-- 框架CSS -->
	<link href="css/flat-ui.css" rel="stylesheet">
	<link href="css/font-awesome.min.css" rel="stylesheet">

	<title>海洋观测系统运行状态监控</title>

	<!-- Bootstrap core CSS -->
	<link href="css/bootstrap.min.css" rel="stylesheet">
	<link href="css/bootstrap.css" rel="stylesheet">

	<!-- Dashboard CSS -->
	<link href="css/dashboard.css" rel="stylesheet">

	<!-- Kendo UI CSS-->
	<link href="css/kendo.dataviz.default.min.css" rel="stylesheet">
	<link href="css/kendo.dataviz.min.css" rel="stylesheet">
	<link href="style/kendo.common.min.css" rel="stylesheet">
	<link href="style/kendo.default.min.css" rel="stylesheet">

	<!-- Modal -->
	<link href="css/bootstrap-modal.css" rel="stylesheet">
	<link href="css/bootstrap-responsive.css" rel="stylesheet">

	<!-- Modal CSS -->
	<style type="text/css">
		body.modal-open,
		.modal-open .navbar-fixed-top,
		.modal-open .navbar-fixed-bottom
		{
			margin-right: 0;
		}
		.modal
		{
			left: 50%;
			bottom: auto;
			right: auto;
			padding: 0;
			width: 500px;
			margin-left: -250px;
			background-color: #ffffff;
			border: 1px solid #999999;
			border: 1px solid rgba(0, 0, 0, 0.2);
			border-radius: 6px;
			-webkit-box-shadow: 0 3px 9px rgba(0, 0, 0, 0.5);
			box-shadow: 0 3px 9px rgba(0, 0, 0, 0.5);
			background-clip: padding-box;
		}
		.modal.container
		{
			max-width: none;
		}
	</style>

	<style type="text/css">
		.btn-circle
		{
			width: 30px;
			height: 30px;
			text-align: center;
			padding: 6px 0;
			font-size: 12px;
			line-height: 1.428571429;
			border-radius: 15px;
			/*background-color:#0000ff;*/
		}
		div.center, p.center, img.center, button.center, h4.center
		{
			margin-left: auto !important;
			margin-right: auto !important;
			float: none !important;
			display: block;
			text-align: center;
		}
		/*<!-- Disk Pie -->*/
		.stats
		{
			text-align: center;
		}
		.pie-list
		{
			margin: 0;
			padding: 0;
			list-style-type: none;
		}
		.pie-list li
		{
			display: inline-block;
			width: 54px;
		}
	</style>
</head>

<body>
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
	<div class="container-fluid" style="background-color:#0A64A4">
		<div class="navbar-header">
			<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
				<span class="sr-only">Toggle navigation</span>
				<span class="icon-bar"></span>
				<span class="icon-bar"></span>
				<span class="icon-bar"></span>
			</button>
			<a class="brand" href="index.html" style="padding-left:20px">
				<img alt="监控icon" src="icons/monitor_48.png">
				<span style="font-size:26px;color:#ffffff;vertical-align:middle">海洋观测系统运行状态监控</span>
			</a>
		</div>

		<div class="navbar-collapse collapse">
			<ul class="nav navbar-nav navbar-right">
				<!--<li><a id="setting" href="#responsive" data-toggle="modal"><span class="icon-cogs"></span>&nbsp;设置</a></li>-->
				<li><a id="message" href="#responsive" data-toggle="modal"><span class="icon-envelope"></span>&nbsp;消息</a></li>
				<li><a id="about" href="#responsive" data-toggle="modal"><span class="icon-question-sign"></span>&nbsp;关于</a>
				</li>
				<li class="dropdown">
					<a href="#user" class="dropdown-toggle" data-toggle="dropdown">
						<span class="icon-user"></span>
						<span id="loginName">&nbsp;用户</span>
						<b class="caret"></b>
					</a>
					<ul class="dropdown-menu">
						<li><a id="account" href="#responsive" data-toggle="modal"><i class="icon-user"></i>&nbsp;账户</a></li>
						<li class="divider"></li>
						<li><a href="login.html" onclick="logout()"><i class="icon-off"></i>&nbsp;退出</a></li>
					</ul>
				</li>
			</ul>
		</div>
	</div>
</div>

<div class="container-fluid">
	<div class="row">
		<div class="col-xs-2 col-sm-2 col-md-2 col-lg-1 sidebar" style="background-color:#2E3538;font-family:'微软雅黑'">
			<ul class="nav nav-sidebar">
				<li>
					<span class="glow"></span>
					<a href="index.html">
						<span class="icon-dashboard icon-2x" style="color:#dfdfdf;"></span>
						<span style="font-size:18px; color:#dfdfdf;">仪表盘</span>
					</a>
				</li>
			</ul>
			<ul class="nav nav-sidebar">
				<li>
					<span class="glow"></span>
					<a href="file.html">
						<span class="icon-file-text icon-2x" style="color:#dfdfdf"></span>
						<span style="font-size:18px; color:#dfdfdf;">&nbsp;文件</span>
					</a>
				</li>
			</ul>
			<ul class="nav nav-sidebar">
				<li class="active">
					<span class="glow"></span>
					<a href="server.html">
						<span class="icon-tasks icon-2x" style="color:#dfdfdf"></span>
						<span style="font-size:18px; color:#dfdfdf;">服务器</span>
					</a>
				</li>
			</ul>
			<ul class="nav nav-sidebar">
				<li>
					<span class="glow"></span>
					<a href="cpu.html">
						<span class="icon-circle-blank icon-2x" style="color:#dfdfdf"></span>
						<span style="font-size:18px; color:#dfdfdf">&nbsp;CPU</span>
					</a>
				</li>
			</ul>
			<ul class="nav nav-sidebar">
				<li>
					<span class="glow"></span>
					<a href="memory.html">
						<span class="icon-ticket icon-2x" style="color:#dfdfdf"></span>
						<span style="font-size:18px; color:#dfdfdf">内存</span>
					</a>
				</li>
			</ul>
			<ul class="nav nav-sidebar">
				<li>
					<span class="glow"></span>
					<a href="disk.html">
						<span class="icon-hdd icon-2x" style="color:#dfdfdf"></span>
						<span style="font-size:18px; color:#dfdfdf">&nbsp;磁盘</span>
					</a>
				</li>
			</ul>
			<ul class="nav nav-sidebar">
				<li>
					<span class="glow"></span>
					<a href="network.html">
						<span class="icon-globe icon-2x" style="color:#dfdfdf"></span>
						<span style="font-size:18px; color:#dfdfdf;">&nbsp;网络</span>
					</a>
				</li>
			</ul>
			<ul class="nav nav-sidebar">
				<li>
					<span class="glow"></span>
					<a href="database.html">
						<span class="icon-calendar icon-2x" style="color:#dfdfdf"></span>
						<span style="font-size:18px; color:#dfdfdf">数据库</span>
					</a>
				</li>
			</ul>
		</div>

		<div class="col-sm-10 col-sm-offset-2 col-md-10 col-md-offset-2 col-lg-11 col-lg-offset-1 main">
			<ul class="breadcrumb">
				<li><a href="index.html">首页</a>
				</li>
				<li class="active">服务器
				</li>
			</ul>
			<!-- Nav tabs -->
			<ul class="nav nav-tabs" id="navTab">

			</ul>

			<!-- Tab panes -->
			<div class="tab-content" id="tabContent">

			</div>
		</div>

	</div>
</div>
<hr>
<footer class="col-xs-12 col-sm-12 col-md-12 col-lg-12" style="margin-bottom:20px">
	<p style="text-align:center">Copyright © 2014 ShangHai Ocean University * Institute For Digital Ocean . All Rights
		Reserved.</p>
</footer>
</div>

<!-- Modal Definitions (tabbed over for <pre>) -->
<div id="responsive" class="modal fade" tabindex="-1" data-width="760" style="display: none;">
	<div class="modal-header">
		<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
		<h4 id="responsiveTitle" class="modal-title" style="text-align:center;font-weight:bold;"></h4>
	</div>
	<div class="modal-body">
		<div class="row">
			<div id="responsiveBody">// class="col-md-offset-1 col-md-10">

			</div>
		</div>
	</div>
	<div class="modal-footer">
		<button type="button" data-dismiss="modal" class="btn btn-default">关闭</button>
		<!--<button type="button" class="btn btn-primary">Save changes</button>-->
	</div>
</div>


<!-- Bootstrap core JavaScript
    ================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="js/jquery.js"></script>
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>

<!-- Modal JS -->
<script src="js/bootstrap-modalmanager.js"></script>
<script src="js/bootstrap-modal.js"></script>

<!-- Kendo UI -->
<script src="js/kendo.dataviz.min.js"></script>
<script src="js/kendo.web.min.js"></script>
<script src="js/kendo.all.min.js"></script>


<script>
	//全局变量声明
	//Server URL
	//    var serverURL = "http://192.168.182.48:8080/api/sql?sql=";
	var serverURL = "http://202.121.66.51:8083/api/sql?sql=";
	//ServerInfo
	var serverCPUInfo;
	//LoopTime
	var loopTime = 5000;
	//ChartHeight
	var chartHeight = 350;
	//DataLimitNumber
	var dataLimitNum = 200;
	//TableLimitNumber
	var tableLimitNum = 8;
	//ChartAxisInterval
	var steps = 10;
	//UpdataArray
	var dataArray = [];
	//cpuCountArray
	var cpuCountArray = [];

	//Responsive <a> 的点击监听事件
	$('a').click(function (e)
	{
		var title = document.getElementById("responsiveTitle");
		var body = document.getElementById("responsiveBody");
		while (body.childNodes.length)
		{
			body.removeChild(body.firstChild);
		}
		console.log(e.target.id);
		body.className = "col-md-offset-1 col-md-10";
//        var resp = document.getElementById("responsive");
//        resp.dataset.width = "760";
//        console.log("target ID:"+e.target.id+"  "+ e.currentTarget);
		switch (e.target.id)
		{
			case "about":
				title.innerText = "关于“海洋观测系统运行状态监控”";
				bodyAbout(body);
				break;
			case "message":
				title.innerText = "消息";
				bodyMessage(body);
				break;
			case "setting":
				title.innerText = "设置";
				bodySetting(body);
				break;
			case "account":
				title.innerText = "账户信息";
				bodyAccount(body);
				break;
			default :
				title.innerText = "Responsive Title";
		}
	});

	// About Body function
	function bodyAbout(fatherDiv)
	{
		var h4 = document.createElement("h4");
		h4.innerText = "介绍：";
		fatherDiv.appendChild(h4);
		var para = document.createElement("p");
		para.innerText = "海洋观测系统运行状态监控是海洋公益性行业科研专项项目“海洋观测系统运行状态监控技术研究与示范”的子项目之一。" +
				"        该系统由国家海洋局东海分局信息中心与上海海洋大学合作研究开发，研发成员有：郭颖新，季丽伟，韦躐晟等。";
		fatherDiv.appendChild(para);
	}
	// Message Body function
	function bodyMessage(fatherDiv)
	{
		var messageDiv = document.createElement("div");
		messageDiv.id = "messageDiv";
		fatherDiv.className = "col-md-12";
		fatherDiv.appendChild(messageDiv);

		var messageInfoSql = "select * from messageInfo group by ID desc limit 200";
		var messageUrl = serverURL + messageInfoSql;
		$.ajax({
			url: messageUrl, //请求的url地址
			dataType: "json", //返回格式为json
			async: true, //请求是否异步，默认为异步，这也是ajax重要特性
			//data:{"id":"value"},    //参数值
			type: "GET", //请求方式
			beforeSend: function ()
			{
				//请求前的处理
			},
			success: function (req)
			{
				//请求成功时处理
				for (var i in req)
				{
					req[i].DateTime = req[i].DateTime.replace("T", " ");
				}
				$("#messageDiv").kendoGrid({
					dataSource: {
						data: req,
						pageSize: 10
					},
					pageable: {
						refresh: true,
						pageSizes: true,
						buttonCount: 5
					},
					navigatable: true,
//                    height: 430,
					scrollable: {
						virtual: true
					},
					sortable: true,
					columns: [{
						field: "ID",
						title: "ID",
						width: 10
					}, {
						field: "ServerID",
						title: "Server",
						width: 20
					}, {
						field: "Aspect",
						title: "方面",
						width: 30
					}, {
						field: "Content",
						title: "内容",
						width: 80
					}, {
						field: "DateTime",
						title: "时间",
						width: 45
					}]
				});
			},
			error: function ()
			{
				//请求出错处理
			}
		});
	}
	// Setting Body function
	function bodySetting(fatherDiv)
	{

	}
	// Account Body function
	function bodyAccount(fatherDiv)
	{
		var userCount = document.createElement("div");
		userCount.id = "userCount";
		fatherDiv.appendChild(userCount);

		var userInfoSql = "select * from user where UserName=\"" + getCookie("loginUser") + "\"";
		var userUrl = serverURL + userInfoSql;
		$.ajax({
			url: userUrl, //请求的url地址
			dataType: "json", //返回格式为json
			async: true, //请求是否异步，默认为异步，这也是ajax重要特性
			//data:{"id":"value"},    //参数值
			type: "GET", //请求方式
			beforeSend: function ()
			{
				//请求前的处理
			},
			success: function (req)
			{
				//请求成功时处理
				$("#userCount").kendoGrid({
					dataSource: {
						data: req
					},
					navigatable: true,
//                    height: 430,
					scrollable: {
						virtual: true
					},
					sortable: true,
					columns: [{
						field: "UserName",
						title: "用户名",
						width: 50
					}, {
						field: "Passwords",
						title: "密码",
						width: 50
					}, {
						field: "Level",
						title: "权限等级",
						width: 40
					}, {
						field: "RegistTime",
						title: "注册时间",
						width: 80
					}, {
						field: "ID",
						title: "ID",
						width: 20
					}]
				});
			},
			complete: function ()
			{
				//请求完成的处理
			},
			error: function ()
			{
				//请求出错处理
			}
		});
	}

	//创建CPUChart
	function createCPUChart(cpuLineID, cpuID, dataSource)
	{
		var lineChartName = "#" + cpuLineID;
		var title = "服务器 " + cpuID + " 使用率";
		$(lineChartName).kendoChart({
			dataSource: {
				data: dataSource
			},
			title: {
				text: title
			},
			legend: {
				visible: false
			},
			chartArea: {
				height: 250
			},
			transitions: false,//重绘：false
			seriesDefaults: {
				type: "area",
//                labels: {
//                    visible: true,
//                    format: "{0}%",
//                    background: "transparent"
//                },
				color: "#0000ff"
			},
			series: [{
				field: "UsedValue",
				name: "CPU"
			}],
			valueAxis: {
				min: 0,
				max: 100,
				labels: {
					format: "{0}%"
				},
				line: {
					visible: true
				}
			},
			categoryAxis: {
				field: "DataTime",
				majorGridLines: {
					visible: true
				},
				type: "date",
				labels: {
					step: steps,
					dateFormats: {}
				},
				baseUnit: "minutes",
				justified: false
			},
			tooltip: {
				visible: true,
				format: "{0}%",
				template: "#= category # - #= value #%"
			}
		});
	}
	//初始化CPUChart
	function initCPUChart(serverID, cpuID, index)
	{
		var cpuDataSql = "select ID,DataTime,UsedValue from cpuuseageinfo where serverid=" + serverID + " and cpuid='" + cpuID + "' order by id desc limit " + dataLimitNum;
		var initDataUrl = serverURL + cpuDataSql;
		var ajInitData = $.ajax({
			url: initDataUrl,
			type: 'get',
			async: false,//true时，由于Ajax异步，updata时，chart可能都未能创建，为确保，设为true；
			dataType: 'json',
			success: function (data)
			{
				if (data.length > 0)
				{
					var div0 = document.createElement("div");
					div0.className = "col-sm-6 col-md-6 col-lg-6 placeholder";
					var div1 = document.createElement("div");
					div1.id = "lineCPUChart" + serverID + cpuID;
					div0.appendChild(div1);

					var fatherId = "panelServer" + serverID + index;
					var element = document.getElementById(fatherId);
					element.appendChild(div0);
					data.reverse();
					for (var i in data)
					{
//                        data[i].DataTime =data[i].DataTime.substr(0,4)+"/"+data[i].DataTime.substr(5,2)+"/"+data[i].DataTime.substr(8,2) + " "+ data[i].DataTime.substr(11,8);
//                        data[i].DataTime =data[i].DataTime.substr(11,8);
						data[i].DataTime = data[i].DataTime.replace("T", " ");
					}
					createCPUChart(div1.id, cpuID, data);
				}
			},
			error: function ()
			{
				alert("异常！");
			}
		});
	}
	//获取CPUCount
	function getCPUCount(serverID)
	{
		// 获取cpuCount值，并初始化cpuLineChart
		var countSql = "select count(*) as cpuCount from (SELECT * FROM cpuuseageinfo where ServerID=" + serverID + " group by CPUID) as a";
		var countUrl = serverURL + countSql;
		$.ajax({
			url: countUrl,    //请求的url地址
			dataType: "json",   //返回格式为json
			async: false,    //请求是否异步，默认为异步，这也是ajax重要特性
//                            data:{"id":"value"},    //参数值
			type: "GET",   //请求方式
			beforeSend: function ()
			{
				//请求前的处理
			},
			success: function (req)
			{
				if (req.length)
				{
					//cpuCount 保存到全局变量cpuCountArray中
					cpuCountArray[serverID - 1] = req[0].cpuCount;
					//请求成功时处理----初始化 服务器-CPU
					for (var j = 0; j < req[0].cpuCount; j++)
					{
						var cpuID = "cpu" + j;
						initCPUChart(serverID, cpuID, 0);
					}
					dataArray[serverID - 1] = "0";
				}
				else
				{
					alert("Server" + serverID + "的CPUCount值获取不到，请检查！");
				}
			},
			complete: function ()
			{
				//请求完成的处理
			},
			error: function ()
			{
				//请求出错处理
			}
		});
	}

	//创建MemoryBar
	function createMemoryBar(barID, valueBar)
	{
		var barName = "#" + barID;
		$(barName).kendoSlider({
			orientation: "vertical",
			value: valueBar,
			min: 0,
			max: 100,
			smallStep: 5,
			largeStep: 10,
			tickPlacement: "both",
			showButtons: false
		});
	}
	//创建MemoryChart
	function createMemoryChart(memoryID, dataMemory)
	{
		var memroyChartName = "#" + memoryID;
//        console.log("Memory Name"+memroyChartName);
		$(memroyChartName).kendoChart({
			dataSource: dataMemory,
			title: {
				text: "内存使用情况监控"
			},
			legend: {
				position: "top"
			},
			chartArea: {
				height: chartHeight
			},
			seriesDefaults: {
				type: "line",
				style: "smooth"
			},
			transitions: false,//重绘：false
			series: [{
				field: "MemorySize",
				name: "内存总量",
				color: "#0000ff"
			}, {
				type: "area",
				field: "MemoryLeft",
				name: "内存剩余",
				color: "#008b00"
			}],
			categoryAxis: {
				field: "DataTime",
				labels: {
					step: steps,
					dateFormats: {}
				},
				type: "date",
				baseUnit: "minutes",
				crosshair: {
					visible: true
				},
				majorGridLines: {
					visible: false
				},
				minorGridLines: {
					visible: true
				},
				justified: false
			},
			valueAxis: {
				labels: {
					format: "{0}"
				}
			},
			tooltip: {
				visible: true,
				shared: true,
				format: "N0"
			}
		});
	}
	//初始化MemoryChart
	function initMemoryChart(serverID, index)
	{
		var memorySql = "select * from physicalmemoryinfo where ServerID=" + serverID + " order by ID desc limit " + dataLimitNum;
		var memoryUrl = serverURL + memorySql;
		$.ajax({
			url: memoryUrl,
			type: 'get',
			dataType: 'json',
			async: false,
			success: function (data)
			{
				if (data.length > 0)
				{
					//Add ProgressBar
					var barF = document.createElement("div");
					barF.className = "col-sm-6 col-md-6 col-lg-6 placeholder";
					var barS = document.createElement("div");
					barS.className = "center";
					barS.id = "barMemoryWeb" + serverID;
					barS.style.width = "30";
					barS.style.height = chartHeight - 50;
					var label = document.createElement("div");
					label.className = "center";
					label.style.fontWeight = "bold";
					label.style.lineHeight = "2";
					label.style.fontSize = "16";
					label.id = "memoryLabel" + serverID;
					label.innerText = "当前内存使用率：" + data[0].MemoUseage + "%";
					barF.appendChild(barS);
					barF.appendChild(label);

					//Add LineChart
					var chartF = document.createElement("div");
					chartF.className = "col-sm-6 col-md-6 col-lg-6 placeholder";
					var chartS = document.createElement("div");
					chartS.id = "lineMemoryChart" + serverID;
					chartF.appendChild(chartS);

					var fatherId = "panelServer" + serverID + index;
					var element = document.getElementById(fatherId);
					element.appendChild(barF);
					element.appendChild(chartF);
					//Bar data
					createMemoryBar(barS.id, data[0].MemoUseage);
					//Chart data
					data.reverse();
					for (var i in data)
					{
//                        data[i].DataTime =data[i].DataTime.substr(0,4)+"/"+data[i].DataTime.substr(5,2)+"/"+data[i].DataTime.substr(8,2) + " "+ data[i].DataTime.substr(11,8);
						data[i].DataTime = data[i].DataTime.substr(11, 8);
//                        console.log("DataTime: "+data[i].DataTime);
					}
					console.log("create Mem chart");
					//
					createMemoryChart(chartS.id, data);
					//内存Chart创建成功，保存状态至dataArray
					dataArray[serverID - 1] = dataArray[serverID - 1] + "1";
				}
				else
				{
					alert("Server" + serverID + "的内存信息无数据！请检查数据库。。。");
				}
			},
			error: function ()
			{
				alert("数据获取失败，请检查网络！");
			}
		});
	}

	//创建DiskPie
	function createDiskPie(pieID, dataArray)
	{
		var pieName = "#" + pieID;
		$(pieName).kendoSparkline({
			type: "pie",
			data: dataArray
		});
	}
	//创建DiskTable
	function createDiskTable(tableID, tableData)
	{
		var tableId = "#" + tableID;
		$(tableId).kendoGrid({
			dataSource: {
				data: tableData
			},
//            height:chartHeight,
			columns: [
				{field: "DiskID", title: "盘符", width: 60},
				{field: "DiskUsed", title: "已用"},
				{field: "DiskLeft", title: "剩余"},
				{field: "DiskUseage", title: "使用率", width: 70},
				{field: "DiskTotal", title: "总大小"},
				{field: "DataTime", title: "时间", width: 170}
			]
		});
	}
	//初始化Disk
	function initDiskChart(serverID, index)
	{
		var diskSql = "select * from (select * from diskinfo where ServerID=" + serverID + " order by DataTime desc) as d group by DiskID";
		var diskUrl = serverURL + diskSql;
		$.ajax({
			url: diskUrl,
			type: 'get',
			dataType: 'json',
			async: false,
			success: function (data)
			{
				if (data.length > 0)
				{
					//Add Pie
					var pieF = document.createElement("div");
					pieF.className = "col-sm-6 col-md-6 col-lg-6 placeholder";
					for (var i in data)
					{
						var pieDiv1 = document.createElement("div");
						pieDiv1.className = "col-sm-3 col-md-3 col-lg-3 placeholder block";
						var pieLabel = document.createElement("div");
						pieLabel.className = "center";
						pieLabel.innerText = "磁盘-" + data[i].DiskID;
						pieDiv1.appendChild(pieLabel);

						var pieChart = document.createElement("div");
						pieChart.className = "center";
						pieChart.id = "pieDisk" + serverID + data[i].DiskID.replace(":", "").replace(".", "");
						pieDiv1.appendChild(pieChart);

						var pieUseage = document.createElement("div");
						pieUseage.id = "pieUseage" + serverID + data[i].DiskID.replace(":", "").replace(".", "");
						pieUseage.className = "center";
						pieUseage.innerText = data[i].DiskUsed + "/" + data[i].DiskTotal;
						pieDiv1.appendChild(pieUseage);

						pieF.appendChild(pieDiv1);
					}
					//Add tables
					var divTable = document.createElement("div");
					divTable.className = "col-sm-6 col-md-6 col-lg-6 placeholder";

					var grid0 = document.createElement("grid");
					grid0.className = "table table-striped table-hover";
					grid0.id = "diskTable" + serverID;
					divTable.appendChild(grid0);

					var fatherId = "panelServer" + serverID + index;
					var element = document.getElementById(fatherId);
					element.appendChild(pieF);
					element.appendChild(divTable);
					//Table data
					var tableData = [];
					for (var j in data)
					{
						tableData[j] = data[j];
						tableData[j].DataTime = tableData[j].DataTime.substr(0, 4) + "/" + tableData[j].DataTime.substr(5, 2) + "/" + tableData[j].DataTime.substr(8, 2) + " " + tableData[j].DataTime.substr(11, 8);
					}
					createDiskTable(grid0.id, tableData);
					//Pie data
					for (var k in data)
					{
						var pieID = "pieDisk" + serverID + data[k].DiskID.replace(":", "").replace(".", "");
						var pieDataArray = [data[k].DiskUsed, data[k].DiskLeft];
//                        console.log("Array():"+pieDataArray[0]+","+pieDataArray[1]);
						createDiskPie(pieID, pieDataArray);
					}
					//内存Chart创建成功，保存状态至dataArray
					dataArray[serverID - 1] = dataArray[serverID - 1] + "2";
				}
				else
				{
					alert("磁盘数据获取失败，请检查！");
				}
			},
			error: function ()
			{
				alert("数据获取失败，请检查网络！");
			}
		});
	}

	//创建NetworkChart
	function createNetworkChart(networkID, dataNetwork)
	{
		var chartID = "#" + networkID;
		$(chartID).kendoChart({
			dataSource: dataNetwork,
			title: {
				text: "网络流量监控"
			},
			legend: {
				position: "bottom"
			},
			chartArea: {
				height: chartHeight
			},
			seriesDefaults: {
				type: "line",
				style: "smooth"
			},
			transitions: false, //重绘：false
			series: [{
				type: "area",
				field: "UpLoagFlux",
				name: "上传 [kb/s]",
				color: "#ff1c1c",
				axis: "speed"
			}, {
				type: "line",
				field: "DownLoadFlux",
				name: "下载 [kb/s]",
				color: "#ffae00",
				axis: "speed"
			}, {
				type: "line",
				field: "InPacketLoss",
				name: "发送丢包 [个]",
				color: "#73c100",
				axis: "outloss"
			}, {
				type: "area",
				field: "OutPacketLoss",
				name: "接收丢包 [个]",
				color: "#007eff",
				axis: "inloss"
			}],
			valueAxes: [{
				name: "inloss",
				color: "#007eff",
				min: 0 //,
				//max: 60
			}, {
				name: "outloss",
				color: "#73c100",
				min: 0 //,
				//max: 60
			}, {
				name: "speed",
				min: 0 //,
				//max: 30
			}],
			categoryAxis: {
				labels: {
					step: steps
				},
				field: "DataTime",
				type: "date",
				baseUnit: "minutes",
				axisCrossingValues: [32, 32, 0],
				justified: false
			},
			tooltip: {
				visible: true,
				format: "{0}",
				template: "#= category # 值: #= value #"
			}
		});
	}
	//创建NetworkTable
	function createNetworkTable(tableID, sourceData)
	{
		var tableId = "#" + tableID;
		$(tableId).kendoGrid({
			dataSource: {
				data: sourceData
			},
			height: chartHeight,
			columns: [
				{field: "DataTime", title: "时间", width: 170},
				{field: "UpLoagFlux", title: "上传速率"},
				{field: "DownLoadFlux", title: "下载速率"},
				{field: "InPacketLoss", title: "in丢包数"},
				{field: "OutPacketLoss", title: "out丢包数"}
			]
		});
	}
	//初始化NetworkChart
	function initNetworkChart(serverID, index)
	{
		var netwrokSql = "select * from NetFluxInfo where ServerID=" + serverID + " order by ID desc limit " + dataLimitNum;
		var networkUrl = serverURL + netwrokSql;
		$.ajax({
			url: networkUrl,
			type: 'get',
			dataType: 'json',
			async: false,
			success: function (data)
			{
				if (data.length > 0)
				{
					//Add LineChart
					var div0 = document.createElement("div");
					div0.className = "col-sm-6 col-md-6 col-lg-6 placeholder";
					var div1 = document.createElement("div");
					div1.id = "lineNetwrokChart" + serverID;
					div0.appendChild(div1);

					//Add tables
					var divTable = document.createElement("div");
					divTable.className = "col-sm-6 col-md-6 col-lg-6 placeholder";

					var grid0 = document.createElement("grid");
					grid0.className = "table table-striped table-hover";
					grid0.id = "lineNetwrokTable" + serverID;
					divTable.appendChild(grid0);

					var fatherId = "panelServer" + serverID + index;
					var element = document.getElementById(fatherId);
					element.appendChild(div0);
					element.appendChild(divTable);
					//Table data
					var tableData = [];
					for (var j = 0; j < tableLimitNum; j++)
					{
						tableData[j] = data[j];
						tableData[j].DataTime = tableData[j].DataTime.substr(0, 4) + "/" + tableData[j].DataTime.substr(5, 2) + "/" + tableData[j].DataTime.substr(8, 2) + " " + tableData[j].DataTime.substr(11, 8);
					}
					tableData.reverse();
					createNetworkTable(grid0.id, tableData);
					//Chart data
					data.reverse();
					for (var i in data)
					{
//                        data[i].DataTime =data[i].DataTime.substr(0,4)+"/"+data[i].DataTime.substr(5,2)+"/"+data[i].DataTime.substr(8,2) + " "+ data[i].DataTime.substr(11,8);
//                        data[i].DataTime =data[i].DataTime.substr(11,8);
						data[i].DataTime = data[i].DataTime.replace("T", " ");
					}
					//调用create Network Chart
					createNetworkChart(div1.id, data);
					//内存Chart创建成功，保存状态至dataArray
					dataArray[serverID - 1] = dataArray[serverID - 1] + "3";
				}
				else
				{
					alert("网络流量数据，获取失败，请检查！");
				}
			},
			error: function ()
			{
				alert("数据获取失败，请检查网络！");
			}
		});
	}

	//更新CPU
	function updateCPU()
	{
		//更新最新CPU useage data
		var updateCPUSQl = "select * from (select * from cpuuseageinfo order by DataTime desc) as d group by ServerID,CPUID";
		var updateCPUUrl = serverURL + updateCPUSQl;
		$.ajax({
			url: updateCPUUrl,    //请求的url地址
			dataType: "json",   //返回格式为json
			async: true,//请求是否异步，默认为异步，这也是ajax重要特性
//                            data:{"id":"value"},    //参数值
			type: "GET",   //请求方式
			beforeSend: function ()
			{
				//请求前的处理
			},
			success: function (req)
			{
				//请求成功时处理
				for (var k in req)
				{
					var updateChartID = "#lineCPUChart" + req[k].ServerID + req[k].CPUID;
					if (($(updateChartID).data("kendoChart")) && ($(updateChartID).data("kendoChart").dataSource.at(dataLimitNum - 1).ID != req[k].ID))
					{
						var chart0 = $(updateChartID).data("kendoChart");
						var firstData = chart0.dataSource.at(0);
						chart0.dataSource.remove(firstData);
//                        req[k].DataTime =req[k].DataTime.substr(11,8);
						req[k].DataTime = req[k].DataTime.replace("T", " ");
						chart0.dataSource.add(req[k]);
					}
				}
			},
			complete: function ()
			{
				//请求完成的处理
			},
			error: function ()
			{
				//请求出错处理
			}
		});
	}
	//更新内存
	function updateMemory()
	{
		//更新最新内存数据
		var updateMemorySQL = "select * from (select * from physicalmemoryinfo order by DataTime desc) as d group by ServerID";
		var updateMemoryUrl = serverURL + updateMemorySQL;
		$.ajax({
			url: updateMemoryUrl,    //请求的url地址
			dataType: "json",   //返回格式为json
			async: true,//请求是否异步，默认为异步，这也是ajax重要特性
//                            data:{"id":"value"},    //参数值
			type: "GET",   //请求方式
			beforeSend: function ()
			{
				//请求前的处理
			},
			success: function (req)
			{
				//请求成功时处理
				for (var k in req)
				{
					var updateChartID = "#barMemoryWeb" + req[k].ServerID;
					var updateBarID = "#lineMemoryChart" + req[k].ServerID;
					if (($(updateChartID).data("kendoChart")) && ($(updateChartID).data("kendoChart").dataSource.at(dataLimitNum - 1).ID != req[k].ID))
					{
						//Update Silder bar
						var newValue = req[k].MemoUseage;
						$(updateBarID).data("kendoSlider").value(newValue);
						var newLabel = document.getElementById("memoryLabel");
						newLabel.innerText = "当前内存使用率：" + req[k].MemoUseage + "%";

						//Update the chart data
						var chart0 = $(updateChartID).data("kendoChart");
						var firstData = chart0.dataSource.at(0);
						chart0.dataSource.remove(firstData);
						req[k].DataTime = req[k].DataTime.substr(11, 8);
						chart0.dataSource.add(req[k]);
					}
				}
			},
			complete: function ()
			{
				//请求完成的处理
			},
			error: function ()
			{
				//请求出错处理
			}
		});
	}
	//更新磁盘
	function updateDisk()
	{
		var diskSql = "select * from (select * from diskinfo order by DataTime desc) as d group by ServerID,DiskID";
		var diskUrl = serverURL + diskSql;
		$.ajax({
			url: diskUrl,
			type: 'get',
			dataType: 'json',
			async: false,
			success: function (data)
			{
				if (data.length > 0)
				{
					//Update Pie
					for (var k in data)
					{
						var pieID = "pieDisk" + data[k].ServerID + data[k].DiskID.replace(":", "");
						var pieLabelID = "pieUseage" + data[k].serverID + data[k].DiskID.replace(":", "");
						if ($(pieID).kendoSparkline)
						{
							$(pieID).kendoSparkline.data = [data[k].DiskUsed, data[k].DiskLeft];
							$(pieLabelID).innerText = data[k].DiskUsed + "/" + data[k].DiskTotal;
						}
					}

					//Table data
					var tableData = [];
					for (var j in data)
					{
						tableData[j] = data[j];
						tableData[j].DataTime = tableData[j].DataTime.substr(0, 4) + "/" + tableData[j].DataTime.substr(5, 2) + "/" + tableData[j].DataTime.substr(8, 2) + " " + tableData[j].DataTime.substr(11, 8);
					}
					var diskTable = "#" + "diskTable" + data[k].ServerID;
					if ($(diskTable).data("kendoGrid"))
					{
						$(diskTable).data("kendoGrid").dataSource = tableData;
					}

				}
			},
			error: function ()
			{
				alert("数据获取失败，请检查网络！");
			}
		});
	}
	//更新网络
	function updateNetwork()
	{
		//更新最新网络流量数据
		var updateNetworkSQL = "select * from (select * from netfluxinfo order by DataTime desc) as d group by ServerID";
		var updateNetworkUrl = serverURL + updateNetworkSQL;
		$.ajax({
			url: updateNetworkUrl,    //请求的url地址
			dataType: "json",   //返回格式为json
			async: true,//请求是否异步，默认为异步，这也是ajax重要特性
//                            data:{"id":"value"},    //参数值
			type: "GET",   //请求方式
			beforeSend: function ()
			{
				//请求前的处理
			},
			success: function (req)
			{
				//请求成功时处理
				for (var k in req)
				{
					var updateChartID = "#lineNetwrokChart" + req[k].ServerID;
					var updateTableID = "#lineNetwrokTable" + req[k].ServerID;

					if (($(updateChartID).data("kendoChart")) && ($(updateChartID).data("kendoChart").dataSource.at(dataLimitNum - 1).ID != req[k].ID))
					{
						if ($(updateTableID).data("kendoGrid"))
						{
							//Update table
							var table0 = $(updateTableID).data("kendoGrid");
							var lastTableData = table0.dataSource.at(0);
							table0.dataSource.remove(lastTableData);
							req[k].DataTime = req[k].DataTime.substr(0, 4) + "/" + req[k].DataTime.substr(5, 2) + "/" + req[k].DataTime.substr(8, 2) + " " + req[k].DataTime.substr(11, 8);
							table0.dataSource.add(req[k]);
						}
						//Update the chart data
						var chart0 = $(updateChartID).data("kendoChart");
						var firstData = chart0.dataSource.at(0);
						chart0.dataSource.remove(firstData);
//                        req[k].DataTime =req[k].DataTime.substr(11,8);
						req[k].DataTime = req[k].DataTime.replace("T", " ");
						chart0.dataSource.add(req[k]);
					}
				}
			},
			complete: function ()
			{
				//请求完成的处理
			},
			error: function ()
			{
				//请求出错处理
			}
		});
	}

	//定时更新
	function loopChartData()
	{
		//第一次循环（根据服务器Number）
		for (var i in serverCPUInfo)
		{
			for (var j in dataArray[i])
			{
				//dataArray中存储着已经被打开过的panel，
				switch (dataArray[i][j])
				{
					case "0":
						updateCPU();
						break;
					case "1":
						updateMemory();
						break;
					case "2":
						updateDisk();
						break;
					case "3":
						updateNetwork();
						break;
					default :
				}
			}
		}
		setTimeout("loopChartData()", loopTime);
	}

	//创建Tab—Panel
	function createTabPanel(serverID, index)
	{
		//Add li to nav
		var li = document.createElement("li");
		if (index == 0)
		{
			li.className = "active";
		}
		var a1 = document.createElement("a");
		a1.href = "#server" + serverID;
		a1.id = "aServer" + serverID;
		a1.dataset.toggle = "tab";
		a1.innerText = "server" + serverID;

		li.appendChild(a1);
		var tab = document.getElementById("navTab");
		tab.appendChild(li);

		//Add tab-panel to tab-content
		var div1 = document.createElement("div");
		if (index == 0)
		{
			div1.className = "tab-pane active";
		}
		else
		{
			div1.className = "tab-pane";
		}
		div1.id = "server" + serverID;

		var br = document.createElement("br");
		div1.appendChild(br);

		var div2 = document.createElement("div");
		div2.className = "panel-group";
		div2.id = "accordion" + serverID;

		//CPU 内存 磁盘 网络 4项
		var itemArray = ["服务器-CPU", "服务器-内存", "服务器-磁盘", "服务器-网络"];
		for (var i = 0; i < 4; i++)
		{
			var div3 = document.createElement("div");
			div3.className = "panel panel-primary";

			var div4 = document.createElement("div");
			div4.className = "panel-heading";

			var h4 = document.createElement("h4");
			h4.className = "panel-title";

			var a2 = document.createElement("a");
			a2.id = "a2" + i + serverID;//a2.id = "a2"+serverID;
			a2.dataset.toggle = "collapse";
			a2.dataset.parent = "#" + div2.id;
			a2.href = "#collapse" + i + serverID;
			a2.onclick = function (e)
			{
				panelClick(e)
			};

			var idata = document.createElement("i");
			idata.className = "icon-chevron-down btn-circle";
			a2.appendChild(idata);
			var textNode = document.createTextNode(itemArray[i]);
			a2.appendChild(textNode);

			h4.appendChild(a2);

			div4.appendChild(h4);
			div3.appendChild(div4);

			var div5 = document.createElement("div");
			div5.id = "collapse" + i + serverID;
			if (i == 0)
			{
				div5.className = "panel-collapse collapse in";
			}
			else
			{
				div5.className = "panel-collapse collapse";
			}

			var div6 = document.createElement("div");
			div6.id = "panelServer" + serverID + i;
			div6.className = "panel-body";

			div5.appendChild(div6);
			div3.appendChild(div5);
			div2.appendChild(div3);

		}
		div1.appendChild(div2);

		var father = document.getElementById("tabContent");
		father.appendChild(div1);
	}

	//监听Tab事件
	$('#navTab').click(function (e)
	{
		e.preventDefault();
//        console.log("Tab0:"+ e.target+"  targetID:"+ e.target.id);
//        console.log("Tab1:"+ e.currentTarget.id+"  releate:"+ e.firstElementChild);
//        console.log("Tab2:"+ $(this).id+"  releate:"+ $(this).className);
		var indexServer = e.target.id[7] - 1;
		var isExist = 0;
		for (var i in dataArray[indexServer])
		{
			if (dataArray[indexServer][i] == "0")
			{
				isExist = 1;
				break;
			}
		}
		if (isExist == 0)
		{
			dataArray[indexServer] = dataArray[indexServer] + "0";
//            initCPUChart(e.target.id[7],cpuID,0);
			getCPUCount(e.target.id[7]);
		}
	});
	//监听子Panel被点击事件
	function panelClick(e)
	{
		var indexServer = e.target.id[3] - 1;
		var isExist = 0;
		for (var i in dataArray[indexServer])
		{
			if (dataArray[indexServer][i] == e.target.id[2])
			{
				isExist = 1;
				break;
			}
		}
		if (isExist == 0)
		{
//            dataArray[indexServer] = dataArray[indexServer]+ e.target.id[2];
//            console.log("e id:"+ e.target.id);
			switch (e.target.id[2])
			{
				case "1"://内存
					console.log("case memory");
					initMemoryChart(e.target.id[3], e.target.id[2]);
					break;
				case "2"://磁盘
					initDiskChart(e.target.id[3], e.target.id[2]);
					break;
				case "3"://网络
					initNetworkChart(e.target.id[3], e.target.id[2]);
					break;
				default :
			}

		}
		//验证cpu(0)、memory(1)、disk(2)、network(3)的数值是否加入成功
		for (var j in dataArray)
		{
//            console.log("dataArray"+j+":"+dataArray[j]);
		}

	}

	// Get Cookie Function
	function getCookie(key)
	{
		var arr = document.cookie.match(new RegExp("(^|)" + key + "=([^;]*)(;|$)"));
		if (arr != null)
		{
			return unescape(arr[2]);
		}
		return null;
	}
	// Delete Cookie
	function deleteCookie(key)
	{
		var exp = new Date();
		exp.setTime(exp.getTime() - 1);
		var cVal = getCookie(key);
		if (cVal != null)
		{
			document.cookie = key + "=" + cVal + ";expires=" + exp.toGMTString();
		}
	}
	// Logout function
	function logout()
	{
		deleteCookie("loginUser");
	}

	//Script Ready Function
	$(document).ready(function ()
	{
		if (!getCookie("loginUser"))
		{
			window.location = "login.html";
		}
		else
		{
			//Init username from cookie
			document.getElementById("loginName").innerText = " " + getCookie("loginUser");
//        var serverInfoSql = "select ServerID,CPUCount from server";
			var serverInfoSql = "select ServerID from server";
			var serverInfoURL = serverURL + serverInfoSql;
			$.ajax({
				url: serverInfoURL,
				type: 'get',
				async: false,
				dataType: 'json',
				success: function (data)
				{
					if (data.length > 0)
					{
						serverCPUInfo = data;
						for (var i in data)
						{
							// Add item to dataArray
							dataArray[i] = "";
							// 创建Tab
							createTabPanel(data[i].ServerID, i);
						}
						// 获取CPU count，并初始化Panel 1 中的CPU
						getCPUCount(data[0].ServerID);
						// 开始计时更新数据
						loopChartData();
					}
				},
				error: function ()
				{
					alert("数据获取失败，请检查网络！");
				}
			});
		}
	});


</script>
</body>
</html>
